package com.zh.filetransport.indicator.impl;

import com.zh.filetransport.indicator.ProgressIndicator
import com.zh.filetransport.model.gson
import com.zh.view.data.ReceiveTaskStore
import com.zh.view.data.SendTaskStore

class DataProgressIndicator : ProgressIndicator {
    private val data = mutableMapOf<String, Any>()
    private var isReceive = false

    init {
        reset()
    }

    private fun reset() {
        data.clear()
        isReceive = false
    }

    override fun bind(id: String, fileName: String, isReceive: Boolean) {
        reset() //重置

        this.isReceive = isReceive
        data["id"] = id
        data["file"] = fileName
    }

    override fun accept(transferredSize: Long, fileSize: Long) {
        if (fileSize == 0L) return

        val progressValue = (transferredSize.toDouble() / fileSize).coerceAtMost(1.0).toFloat()

        if (isReceive) {
            ReceiveTaskStore.setProgressValueById(progressValue, data["id"].toString())
        } else {
            SendTaskStore.setProgressValueById(progressValue, data["id"].toString())
        }
//      printProgress()
    }

    @Synchronized
    private fun printProgress() {
        try {
            data["isReceive"] = isReceive
            val json = gson.toJson(data)
            println("[progress] $json")
            System.out.flush()
            data.remove("isReceive")
        } catch (e: Exception) {
            System.err.println("json格式化出错. ${e.message}")
        }
    }
}